﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Provider;
using System.Data;
using System.Data.Common;
using System.Web;
using System.Web.Security;
using System.Text;

namespace phpBB
{

    /// <summary>
    /// PHPBBMembershipProvider that utilizes the phpBBDatabaseInterface.
    /// </summary>
    public class phpBBMembershipProvider : MembershipProvider, ISyncAuthentication, ISyncAuthenticationTool
    {
        /// <summary>
        /// phpBBDatabaseInterface that is used to perform the actions.
        /// </summary>
        private phpBBDatabaseInterface DatabaseInterface
        {
            get;
            set;
        }

        /// <summary>
        /// Registration is done by redirection to the phpBB redirection site of phpBB
        /// The URL is build by the phpBBDatabaseInterface
        /// </summary>
        public string RegistrationURL
        {
            get
            {
                return DatabaseInterface.RegistrationURL;
            }
        }

        /// <summary>
        /// Initialization of the inherited properties and the phpBBDatabaseInterface
        /// </summary>
        /// <param name="name"></param>
        /// <param name="config"></param>
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config must not be null.");
            }

            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "phpBB Membership Provider");
            }

            base.Initialize(name, config);
            
            _EnablePasswordReset = true;
            if (config["enablePasswordReset"] != null)
            {
                _EnablePasswordReset = bool.Parse(config["enablePasswordReset"]);
            }
            
            _MaxInvalidPasswordAttempts = 0;
            if (config["maxInvalidPasswordAttempts"] != null)
            {
                _MaxInvalidPasswordAttempts = int.Parse(config["maxInvalidPasswordAttempts"]);
            }
            
            _MinRequiredNonAlphanumericCharacters = 0;
            if (config["minRequiredNonAlphanumericCharacters"] != null)
            {
                _MinRequiredNonAlphanumericCharacters = int.Parse(config["minRequiredNonAlphanumericCharacters"]);
            }
            
            _MinRequiredPasswordLength = 0;
            if (config["minRequiredPasswordLength"] != null)
            {
                _MinRequiredPasswordLength = int.Parse(config["minRequiredPasswordLength"]);
            }
            
            _PasswordAttemptWindow = 15;
            if (config["passwordAttemptWindow"] != null)
            {
                _PasswordAttemptWindow = int.Parse(config["passwordAttemptWindow"]);
            }
            
            _PasswordStrengthRegularExpression = "";
            if (config["passwordStrengthRegularExpression"] != null)
            {
                _PasswordStrengthRegularExpression = config["passwordStrengthRegularExpression"];
            }
            
            DatabaseInterface = phpBBDatabaseInterface.getSingleton();
            DatabaseInterface.Initialize(config);
        }

        #region Inherited properties
        private bool _EnablePasswordRetrieval = true;
        public override bool EnablePasswordRetrieval
        {
            get
            {
                return _EnablePasswordRetrieval;
            }
        }

        private bool _EnablePasswordReset = true;
        public override bool EnablePasswordReset
        {
            get
            {
                return _EnablePasswordReset;
            }
        }

        private bool _RequiresQuestionAndAnswer = false;
        public override bool RequiresQuestionAndAnswer
        {
            get
            {
                return _RequiresQuestionAndAnswer;
            }
        }

        private string _ApplicationName = "";
        public override string ApplicationName
        {
            get
            {
                return _ApplicationName;
            }
            set
            {
                _ApplicationName = value;
            }

        }

        private int _MaxInvalidPasswordAttempts = 3;
        public override int MaxInvalidPasswordAttempts
        {
            get
            {
                return _MaxInvalidPasswordAttempts;
            }
        }

        private int _PasswordAttemptWindow = 5;
        public override int PasswordAttemptWindow
        {
            get
            {
                return _PasswordAttemptWindow;
            }
        }

        private bool _RequiresUniqueEmail = true;
        public override bool RequiresUniqueEmail
        {
            get
            {
                return _RequiresUniqueEmail;
            }
        }

        private MembershipPasswordFormat _PasswordFormat = MembershipPasswordFormat.Hashed;
        public override MembershipPasswordFormat PasswordFormat
        {
            get
            {
                return _PasswordFormat;
            }
        }

        private int _MinRequiredPasswordLength = 5;
        public override int MinRequiredPasswordLength
        {
            get
            {
                return _MinRequiredPasswordLength;
            }
        }

        private int _MinRequiredNonAlphanumericCharacters = 0;
        public override int MinRequiredNonAlphanumericCharacters
        {
            get
            {
                return _MinRequiredNonAlphanumericCharacters;
            }
        }

        private string _PasswordStrengthRegularExpression = "";
        public override string PasswordStrengthRegularExpression
        {
            get
            {
                return _PasswordStrengthRegularExpression;
            }
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion,
            string passwordAnswer, bool isApproved, Object providerUserKey, out MembershipCreateStatus status)
        {
            status = MembershipCreateStatus.ProviderError;
            return null;
        }
        
        #endregion

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="newPasswordQuestion"></param>
        /// <param name="newPasswordAnswer"></param>
        /// <returns></returns>
        public override bool ChangePasswordQuestionAndAnswer(string username, string password,
            string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="username"></param>
        /// <param name="answer"></param>
        /// <returns></returns>
        public override string GetPassword(string username, string answer)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="username"></param>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="username"></param>
        /// <param name="answer"></param>
        /// <returns></returns>
        public override string ResetPassword(string username, string answer)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="user"></param>
        public override void UpdateUser(MembershipUser user)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Validation via the phpBBDatabaseInterface
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>User could be validated or not</returns>
        public override bool ValidateUser(string username, string password)
        {
            return DatabaseInterface.ValidateUser(username,password);
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public override bool UnlockUser(string userName)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="providerUserKey"></param>
        /// <param name="userIsOnline"></param>
        /// <returns></returns>
        public override MembershipUser GetUser(Object providerUserKey, bool userIsOnline)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="username"></param>
        /// <param name="userIsOnline"></param>
        /// <returns></returns>
        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public override string GetUserNameByEmail(string email)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported. Users may not be deleted.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="deleteAllRelatedData"></param>
        /// <returns></returns>
        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecords"></param>
        /// <returns></returns>
        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported yet. Could be read from phpBB database
        /// </summary>
        /// <returns></returns>
        public override int GetNumberOfUsersOnline()
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="usernameToMatch"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecords"></param>
        /// <returns></returns>
        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Not supported
        /// </summary>
        /// <param name="emailToMatch"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecords"></param>
        /// <returns></returns>
        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Method is NOT inherited from MembershipProvider
        /// Sets cookies for phpBB-Forum and creates session
        /// </summary>
        /// <param name="username"></param>
        /// <param name="rememberMe"></param>
        public void LogOn(string username, bool rememberMe)
        {
            DatabaseInterface.SetCookies(username, rememberMe);
        }

        /// <summary>
        /// Method is NOT inherited from MembershipProvider
        /// SignOut phpBB-forum
        /// </summary>
        public void SignOut()
        {
            DatabaseInterface.SignOut();
        }

        /// <summary>
        /// CheckAuthentication: 
        /// Following cases can happen:
        /// 1) Nothing changes in the authentication status of .NET and phpbb 
        ///    => No change
        /// 2) .NET ist still authenticated but phpbb is logged out
        ///    => Log out .NET
        /// 3) .NET is not authenticated but phpbb is logged in
        ///    => Log in .NET
        /// 4) .NET gets authenticated and cookies show phpbb still logged out
        ///    => No change
        /// 5) .NET gets logged out and coockies show phpbb still loggen in
        ///    => No change
        /// </summary>

        public void Sync()
        {
            string userName = "";
            bool rememberMe = false;

            if (IsAuthenticated(out userName, out rememberMe))
            {
                if (!FormsIsAuthenticated())
                {
                    FormsAuthentication.SetAuthCookie(userName, rememberMe);
                    ReloadPage();
                }
            }
            else
            {
                if (FormsIsAuthenticated())
                {
                    FormsAuthentication.SignOut();
                    ReloadPage();
                }
            }
        }


        /// <summary>
        /// Method is NOT inherited from MembershipProvider
        /// Checks if current user is authenticated at phpBB-forum
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="rememberMe"></param>
        /// <returns></returns>
        public bool IsAuthenticated(out string UserName, out bool rememberMe)
        {
            return DatabaseInterface.IsAuthenticated(out UserName, out rememberMe);
        }

        /// <summary>
        /// Method is NOT inherited from MembershipProvider
        /// Returns whether user is authenticated at .NET
        /// </summary>
        /// <returns>Returns whether user is authenticated at .NET</returns>
        public bool FormsIsAuthenticated()
        {
            return HttpContext.Current.Request.IsAuthenticated;
        }

        /// <summary>
        /// Method is NOT inherited from MembershipProvider
        /// Helper method that reloads the current page, so that changes at cookies are 
        /// propagated into the request in the current HttpContext.
        /// </summary>
        public void ReloadPage()
        {
            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri);
        }
    }
}
